package com.ytrsoft.ws;

import com.ytrsoft.bean.Message;

import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCode;
import javax.websocket.RemoteEndpoint;
import java.io.IOException;
import javax.websocket.Session;

public class BaseSocket {

    private String id;
    private Session session;

    public BaseSocket() {
        this.initialized();
    }

    protected void initialized() {}

    public void close(CloseCode code, String reason) {
        try {
            session.close(new CloseReason(code, reason));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void postMessage(Message message) {
        if (session != null) {
            try {
                RemoteEndpoint.Basic remote = session.getBasicRemote();
                remote.sendText(message.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
